<template>
  <!-- 添加或修改对话框 -->
  <el-dialog :title="title" :visible.sync="visible" width="1100px" append-to-body :close-on-click-modal="false">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="模板名称" prop="templateName">
            <el-input v-model="form.templateName" placeholder="请输入模板名称" maxlength="30" show-word-limit/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" v-if="this.form.id">
          <el-form-item label="创建人" prop="createUserName">
            <el-input v-model="form.createUserName" :disabled="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="this.form.id">
          <el-form-item label="创建时间" prop="createTime">
            <el-input v-model="form.createTime" :disabled="true"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-divider>告警模板信息</el-divider>
          <el-button @click="addTemplateAttr" style="margin-bottom: 15px" type="primary" size="mini">新增字段
          </el-button>
          <el-table :data="form.templateNodes" style="width:100%" height="330" border>
            <el-table-column prop="sort" label="排序" width="120" fixed>
              <template slot-scope="scope">
                <el-input v-model="scope.row.sort" autocomplete="off" size="small" type="number" :min="0"/>
              </template>
            </el-table-column>
            <el-table-column prop="fieldKey" label="字段名" width="320">
              <template slot-scope="scope">
                <el-input v-model="scope.row.fieldKey" clearable autocomplete="off" size="small" placeholder="请输入字段名"
                          maxlength="15" show-word-limit/>
              </template>
            </el-table-column>
            <el-table-column prop="fieldValue" label="字段值" width="430">
              <template slot-scope="scope">
                <div style="display: flex; align-items: center;">
                  <el-select v-model="scope.row.fieldType" clearable style="width:110px;flex-shrink: 0;"
                             placeholder="字段类型"
                             @change="handleFieldValueChange(scope.row)">
                    <el-option
                      v-for="item in fieldTypeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                  <el-select v-if="scope.row.fieldType === '1'" clearable v-model="scope.row.fieldValue"
                             style="width:100%;"
                             placeholder="请选择内置字段值">
                    <el-option
                      v-for="item in fieldValueOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                  <el-input v-else v-model="scope.row.fieldValue"
                            style="flex: 2;" autocomplete="off" size="small" placeholder="表达式定义规则:${变量名}"
                            maxlength="35" show-word-limit/>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="alarmOut" label="告警输出" width="80">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.alarmOut" @change="changeCheck($event,'alarmOut', scope.row)">是
                </el-checkbox>
              </template>
            </el-table-column>
<!--            <el-table-column prop="formOut" label="表单输出" width="80">-->
<!--              <template slot-scope="scope">-->
<!--                <el-checkbox v-model="scope.row.formOut" @change="changeCheck($event,'formOut', scope.row)">是-->
<!--                </el-checkbox>-->
<!--              </template>-->
<!--            </el-table-column>-->
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" plain style="color: red;"
                           @click="removeTemplateAttr(scope.$index, scope.row)"
                           :disabled="scope.row.nonDeletable === 1">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
  import {
    defaultTemplate,
    addTemplate,
    updateTemplate
  } from "@/api/hawkeye/template";

  export default {
    name: "TemplateModalForm",
    props: {},
    data() {
      return {
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        visible: false,
        defaultTemplateNodes: [],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          templateName: [
            {required: true, message: "模板名称不能为空", trigger: "blur"}
          ]
        },
        fieldTypeOptions: [{
          label: '内置',
          value: '1'
        }, {
          label: '自定义',
          value: '2'
        }],
        fieldValueOptions: [{
          label: '链路ID',
          value: '${tid}'
        },
          {
            label: '服务名',
            value: '${serviceName}'
          },
          {
            label: '入口地址',
            value: '${entranceUri}'
          },
          {
            label: '请求地址',
            value: '${requestUri}'
          },
          {
            label: '告警时间',
            value: '${@timestamp}'
          },
          {
            label: '异常信息',
            value: '${message}'
          },
          {
            label: '异常文件',
            value: '${errorFileName}'
          },
          {
            label: '异常名称',
            value: '${errorName}'
          },
          {
            label: '异常堆栈',
            value: '${stackTrace}'
          },
          {
            label: '进程ID',
            value: '${pid}'
          },
          {
            label: '线程号',
            value: '${thread}'
          },
          {
            label: '频度等级',
            value: '${alarmLevel}'
          },
          {
            label: '类路径',
            value: '${className}'
          },
          {
            label: '方法名称',
            value: '${methodName}'
          }]
      };
    },
    created() {
      if (this.checkPermi(['hawk-eye:template:query'])) {
        this.getDefaultTemplate();
      }
    },
    methods: {
      open(row) {
        this.reset();
        if (row && row.id) {
          this.form = row;
          this.title = "编辑";
        } else {
          this.title = "添加";
        }
        this.visible = true;
      },
      copy(row) {
        let suffix = "-copy";
        const regex = /-copy\d+$/;
        let dest = Object.assign({}, row);
        this.reset();
        if (dest.templateName.endsWith(suffix)) {
          dest.templateName = `${dest.templateName}2`
        } else if (regex.test(dest.templateName)) {
          let suffixIndex = dest.templateName.lastIndexOf(suffix);
          let numberStr = dest.templateName.substring(suffixIndex + suffix.length);
          let number = parseInt(numberStr);
          let next = number + 1;
          dest.templateName = dest.templateName.substring(0, suffixIndex + suffix.length) + next;
        } else {
          dest.templateName = `${dest.templateName}-copy`
        }
        dest.id = undefined;
        this.title = "复制";
        this.form = dest;
        this.visible = true;
      },
      getDefaultTemplate() {
        defaultTemplate().then(res => {
          this.defaultTemplateNodes = res.data || [];
        })
      },
      // 取消按钮
      cancel() {
        this.visible = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.getDefaultTemplate();
        this.form = {
          id: null,
          templateName: null,
          templateNodes: this.defaultTemplateNodes || []
        };
        this.resetForm("form");
      },
      addTemplateAttr() {
        let max = 0;
        if (this.form.templateNodes) {
          for (let i = 0; i < this.form.templateNodes.length; i++) {
            if (this.form.templateNodes[i].sort > max) {
              max = this.form.templateNodes[i].sort;
            }
          }
        }
        this.form.templateNodes.push({
          id: null,
          fieldKey: '',
          fieldValue: '',
          formOut: true,
          alarmOut: true,
          formOutType: '1',
          sort: max + 1,
        })
      },
      removeTemplateAttr(index, row) {
        this.form.templateNodes.splice(index, 1);
      },
      handleFieldValueChange(row) {
        row.fieldValue = ''
      },
      // 列表复选框的change事件
      changeCheck(value, field, row) {
        this.$set(row, field, value)
      },
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            //去除空字段
            // this.form.templateNodes = Array.from(this.form.templateNodes).filter(item => {
            //   let filter = true;
            //   for (let key in item) {
            //     if ("fieldDefaultValue" === key || "type" === key) {
            //       continue;
            //     }
            //     if (item.hasOwnProperty(key)) {
            //       if (item[key] === null || item[key] === undefined) {
            //         filter = false;
            //         break;
            //       }
            //     }
            //   }
            //   return filter;
            // })
            if (this.form.id != null) {
              updateTemplate(this.form).then(res => {
                this.$modal.msgSuccess("修改成功");
                this.visible = false;
                this.$emit('submitted', res);
              });
            } else {
              addTemplate(this.form).then(res => {
                this.$modal.msgSuccess("新增成功");
                this.visible = false;
                this.$emit('submitted', res);
              });
            }
          }
        });
      },
    }
  }
</script>
